package com.kehutong.payfees.service;

//import com.kehutong.common.DoveClient;
//import com.kehutong.common.errcode.ErrorCode;
//import com.kehutong.common.errcode.Result;
//import com.kehutong.common.urlconfig.FileUrlConfig;
//import com.kehutong.common.urlconfig.WorkerUrlConfig;
//import com.kehutong.common.util.Token;
//import com.kehutong.payfees.dto.*;
//import com.kehutong.payfees.entity.ChargeLawyerMaterial;
//import com.kehutong.payfees.entity.ChargeMediation;
//import com.kehutong.payfees.enums.ChargeLawyerMaterialStatus;
//import com.kehutong.payfees.enums.ChargeLawyerMaterialType;
//import com.kehutong.payfees.util.BasicClient;
//import com.kehutong.payfees.util.StringUtils;
//import org.coraframework.http.HttpClient;
//import org.coraframework.inject.Inject;
//import org.coraframework.json.JSONArray;
//import org.coraframework.json.JSONObject;
//import org.coraframework.mvc.webservice.WebService;
//import org.coraframework.orm.Pool;
//import org.coraframework.orm.jdbc.SQLSession;
//import org.coraframework.util.CallBack;
//import org.coraframework.util.EnumUtil;
//import org.coraframework.util.Objects;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.concurrent.atomic.AtomicReference;
//
//@WebService("/charge/lawyer/material")
//public class ChargeLawyerMaterialServiceImpl {
//
//    @Inject
//    private DoveClient doveClient;
//    @Inject
//    private BasicClient basicClient;
//    @Inject
//    private SQLSession sqlSession;
//
//    @Inject
//    private EnterpriseService enterpriseService;
//
//    @Inject
//    private FileUrlConfig fileUrlConfig;
//
//    @Inject
//    private WorkerUrlConfig workConfig;

//    @Inject
//    private AuthEnterpriseService authEnterpriseService;
//
//    @Inject
//    private SuiteSettingService suiteSettingService;
//
//    public Object getChargeLawyerMaterialList(JSONObject jsonObject) {
//        return sqlSession.findArray(ChargeLawyerMaterial.class)
//                .eq("chargeMediationId", jsonObject.getString("id"))
//                .eq("type", EnumUtil.getEnum(ChargeLawyerMaterialType.class, jsonObject.getString("type")))
//                .eq("deleted", false).exe();
//    }
//
//    public void saveChargeLawyerMaterial(ChargeLawyerMaterial chargeLawyerMaterial) {
//        sqlSession.insert(chargeLawyerMaterial);
//    }
//
//    public String getContactUserId(String id) {
//        WebChat webChat = Pool.get(WebChat.class, id);
//        if (Objects.isNull(webChat)) {
//            return null;
//        }
//
//        Contact contact = sqlSession.findOne(Contact.class)
//                .eq("unionid", webChat.getUnionid())
//                .eq("deleted", false).exe();
//        if (Objects.isNull(contact)) {
//            return null;
//        }
//
//        return contact.getUserId();
//    }
//
//    public Object sendChargeLawyerMaterial(Token token, JSONObject jsonObject)  throws Exception {
//        String id = jsonObject.getString("id");
//        ChargeLawyerMaterial chargeLawyerMaterial = Pool.get(ChargeLawyerMaterial.class, id);
//        ChargeMediation chargeMediation = Pool.get(ChargeMediation.class, chargeLawyerMaterial.getChargeMediationId());
//
//        String respondentUserId = jsonObject.getString("userId");
//        String employeeNo = jsonObject.getString("employeeNo");
//        String handlerNo = jsonObject.getString("handlerNo");
//        if (Objects.isEmpty(respondentUserId) && Objects.isEmpty(employeeNo) && Objects.isEmpty(handlerNo)) {
//            return Result.error(-1, "无可发送人！");
//        }
//
//        if (Objects.nonEmpty(respondentUserId)) {
//            JSONObject resultJSON = sendContactByUserId(jsonObject, chargeLawyerMaterial);
//            if (Objects.nonEmpty(resultJSON.getJSONArray("fail_list"))) {
//                return Result.error(-1, "被申请人发送无效或无法发送！");
//            }
//
//            if (resultJSON.getInteger("code") == 41048) {
//                return Result.error(-1, "发送次数超过4次，被申请人发送失败！");
//            }
//            chargeLawyerMaterial.setStatus(ChargeLawyerMaterialStatus.SENDED);
//
//            if (Objects.isEmpty(employeeNo) && Objects.isEmpty(handlerNo)) {
//                sqlSession.updateById(chargeLawyerMaterial);
//                return Result.success("发送成功！");
//            }
//        }
//
//        if (Objects.nonEmpty(employeeNo)) {
//            JSONObject employee = basicClient.getEmployeeById(token, employeeNo);
//            // 获取SuiteSetting
//
//            JSONObject json = doveClient.post("", (http) -> {  //todo 地址
//            });
//            JSONArray suiteList = json.getJSONArray("data");
//
//            List<SuiteSetting> suiteList = suiteSettingService.getSuiteSettingList(chargeMediation.getCompanyNo());
//            if (Objects.isEmpty(suiteList)) {
//                return Result.error(-1, "发生错误！");
//            }
//            SuiteSetting setting = (SuiteSetting)suiteList.get(0);
//            sendEmployeeByUserId(jsonObject, employee.getString("userid"), setting, chargeLawyerMaterial);
//        }
//
//
//        if (Objects.nonEmpty(handlerNo)) {
//            JSONObject employee = basicClient.getEmployeeById(token, handlerNo);
//            // 获取SuiteSetting
//            JSONObject json = doveClient.post("", (http) -> {  //todo 地址
//                http.addParam("companyNo", chargeMediation.getHandlerCompanyNo());
//            });
//            JSONArray suiteList = json.getJSONArray("data");
//            List<SuiteSetting> suiteList = suiteSettingService.getSuiteSettingList(chargeMediation.getHandlerCompanyNo());
//            if (Objects.isEmpty(suiteList)) {
//                return Result.error(-1, "发生错误！");
//            }
//            SuiteSetting setting = (SuiteSetting)suiteList.get(0);
//            sendEmployeeByUserId(jsonObject, employee.getString("userid"), setting, chargeLawyerMaterial);
//        }
//
//        chargeLawyerMaterial.setStatus(ChargeLawyerMaterialStatus.SENDING);
//        sqlSession.updateById(chargeLawyerMaterial);
//        return Result.success();
//    }
//
//    public void updateTaskCardClick(String id) {
//        ChargeLawyerMaterial chargeLawyerMaterial = Pool.get(ChargeLawyerMaterial.class, id);
//        chargeLawyerMaterial.setStatus(ChargeLawyerMaterialStatus.SENDED);
//        sqlSession.updateById(chargeLawyerMaterial);
//    }

//    private JSONObject sendContactByUserId(JSONObject jsonObject, ChargeLawyerMaterial chargeLawyerMaterial) throws Exception {
//        JSONObject resJson = doveClient.post("", (http) -> {  //todo 地址
//        });
//
//        final String access_token = resJson.getString("data");
//        final CallBack<HttpClient> httpCallBack = http -> {
//            http.addParam("access_token", access_token);
//            JSONObject json = new JSONObject();
//            json.put("chat_type", "single");
//            json.put("external_userid", jsonObject.getString("userId"));
//
//            JSONObject link = new JSONObject();
//            link.put("title", chargeLawyerMaterial.getFileName());
//            link.put("desc", jsonObject.getString("desc"));
//            link.put("picurl", fileUrlConfig.getUrl("/file/view", "isBig", "true", "id", chargeLawyerMaterial.getFileId()));
//            if (Objects.equal(chargeLawyerMaterial.getFileSuffix(), ".pdf")) {
//                link.put("url", fileUrlConfig.getFile(chargeLawyerMaterial.getFileId(), true));
//            }else {
//                link.put("url", fileUrlConfig.getVideo(chargeLawyerMaterial.getFileId()));
//            }
//
//            json.put("link", link);
//            http.setBody(json.toJSONString());
//        };
//        AtomicReference<JSONObject> jsonObjectAtomic = new AtomicReference<>();
////        ErrorCode rs = workConfig.post("/cgi-bin/externalcontact/add_msg_template", httpCallBack, jsonObjectAtomic::set);
//
//        ErrorCode rs = ErrorCode.OK;
//
//        JSONObject resultJson = jsonObjectAtomic.get();
//        if (Objects.isNull(resultJson)) {
//            resultJson = new JSONObject();
//        }
//
//        resultJson.put("code", rs.code);
//        return resultJson;
//    }

//    /**
//     * 发送到员工(申请人&律师)
//     * @param jsonObject
//     * @param userid
//     * @param setting
//     * @param chargeLawyerMaterial
//     * @throws Exception
//     */
//    private void sendEmployeeByUserId (JSONObject jsonObject, String userid, SuiteSetting setting, ChargeLawyerMaterial chargeLawyerMaterial) throws Exception {
//        JSONObject resJson = doveClient.post("", (http) -> {  //todo 地址
//            http.addParam("suiteNo", setting.getId());
//            http.addParam("force", "false");
//        });
//        final String access_token = resJson.getString("data");
//        final String access_token = suiteSettingService.getAppAccessToken(setting.getId(), false);

//        workConfig.post("/cgi-bin/message/send", http -> {
//            http.addParam("access_token", access_token);
//
//            JSONObject json = new JSONObject();
//            json.put("touser", userid);
//            json.put("msgtype", "taskcard");
//            json.put("agentid", getAgentid(setting));
//
//            JSONObject taskcard = new JSONObject();
//            taskcard.put("title", chargeLawyerMaterial.getFileName());
//            taskcard.put("description", Objects.nonEmpty(jsonObject.getString("desc")) ? jsonObject.getString("desc") : chargeLawyerMaterial.getFileName());
//            if (Objects.equal(chargeLawyerMaterial.getFileSuffix(), ".pdf")) {
//                taskcard.put("url", fileUrlConfig.getFile(chargeLawyerMaterial.getFileId(), true));
//            }else {
//                taskcard.put("url", fileUrlConfig.getVideo(chargeLawyerMaterial.getFileId()));
//            }
//            taskcard.put("task_id", StringUtils.randomUUID());
//
//            List<JSONObject> listBtn = new ArrayList<>();
//
//            JSONObject btn = new JSONObject();
//            btn.put("key", chargeLawyerMaterial.getId());
//            btn.put("name", "待接收");
//            btn.put("replace_name", "已接收");
//            listBtn.add(btn);
//            taskcard.put("btn", listBtn);
//
//            json.put("taskcard", taskcard);
//            http.setBody(json.toJSONString());
//        });
//    }
//
//    /**
//     * 获取Agentid
//     * @param setting
//     * @return
//     * @throws Exception
//     */
//    private String getAgentid(SuiteSetting setting) throws Exception {
//        AppSetting appSetting = Pool.get(AppSetting.class, setting.getAppNo());
//        if (Objects.isEmpty(setting.getPermanentCode())) {
//            return appSetting.getAppId();
//        } else {
//            JSONObject resJson = doveClient.post("", (http) -> {  //todo 地址
//                http.addParam("appId", appSetting.getAppId());
//            });
//            String data = resJson.getString("data");
//            AuthEnterprise enterprise = JSONObject.parseObject(data, AuthEnterprise.class);
//            return enterprise.getAgentid();
//        }
//    }
//}
